<template>
    <div>
        <el-upload :action="action" :before-upload="beforeUpload" :http-request="uploadRequest" :file-list="fileList"
            list-type="picture-card" :on-preview="handlePreview" :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
            <div slot="tip" v-if="uploadTip" class="el-upload__tip">{{ uploadTip }}</div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" width="50%">
            <img :src="dialogImageUrl" alt="预览" style="width: 100%" />
        </el-dialog>
    </div>
</template>

<script>
import { Message } from 'element-ui';
import axios from "~/plugins/axios.js";

export default {
    name: 'UploadImage',
    props: {
        fileList: {
            type: Array,
            default: () => []
        },
        maxFiles: {
            type: Number,
            default: 1
        },
        uploadTip: {
            type: String,
            default: null
        },
    },
    data() {
        return {
            dialogVisible: false,
            dialogImageUrl: '',
            isUploading: false,
            action: '/admin/file.File/add'
        };
    },
    methods: {
        beforeUpload() {
            if (this.isUploading) {
                Message.warning('正在上传中，请等待当前上传完成');
                return false;
            }

            if (this.fileList.length >= this.maxFiles) {
                Message.warning('只能上传一张图片');
                return false;
            }
            return true;
        },

        handleRemove(file) {
            const index = this.fileList.findIndex(f => f.url === file.url);
            if (index !== -1) {
                this.fileList.splice(index, 1);
            }
        },

        handlePreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        async uploadRequest(file) {
            this.isUploading = true;
            const formData = new FormData();
            formData.append('type', 'upl');
            formData.append('file', file.file);
            formData.append('file_type', 'image');
            try {
                const res = await axios.post(this.action, formData);
                if (res.code === 200) {
                    Message.success('图片上传成功');
                    this.fileList.push({
                        file_id: res.data.file_id,
                        url: res.data.file_url,
                        name: res.data.file_name
                    });
                } else {
                    Message.error('图片上传失败');
                }
            } catch (error) {
                Message.error('上传请求失败');
            } finally {
                this.isUploading = false;
            }
        }
    }
}
</script>

<style scoped lang="less">
.el-upload__tip {
    margin-top: 0;
}
</style>